<?php defined('SYSPATH') or die('No direct script access.');

class Model_Brand extends Model_Filter
{      
    public function get_brands($category = null, $brand = null, $color = null, $composition = null, $season = null, $shop = null, $price = null, $use_denormalization = true, $disable_cache = false)
    {        
        $stat = array();
        
        $ids = array();
        $category_id = self::_get_category_id($category, $ids);
        
        $brand_id    = self::_get_brand_id($brand);
        
        $color_id    = self::_get_color_id($color);
        
        $composition_id = self::_get_composition_id($composition);
        
        $season_id   = self::_get_season_id($season);
        
        $shop_id     = self::_get_shop_id($shop);
        
        $from_price  = self::_get_from_price($price);
        $to_price    = self::_get_to_price($price);
        
        if (!$disable_cache && $brands = Cache::instance()->get('catalog_brands_'.$category_id.'_'.$brand_id.'_'.$color_id.'_'.$composition_id.'_'.$season_id.'_'.$shop_id.'_'.$from_price.'_'.$to_price)) {
            return $brands;
        }
        
        $isset_denormalized_data = null;
        if ($use_denormalization) {
            // Узнаем, используется ли денормализация
            $isset_denormalized_data = self::_isset_denormalized_data($category_id, $brand_id, $color_id, $composition_id, $season_id, $shop_id, $price);   
        }
        
        $tmp_stat = DB::select('brand_id', array(DB::expr('COUNT( * )'), 'count'))
                    ->from('products')
                    ->where('is_available', '=', 1);
                    
        $current_brand_stat = DB::select(array(DB::expr('COUNT( * )'), 'count'))
                                ->from('products')
                                ->where('is_available', '=', 1);
                    
        if (is_array($ids) && count($ids) > 0) {
            $tmp_stat->where('category_id', 'IN', $ids);
            $current_brand_stat->where('category_id', 'IN', $ids);
        }
                    
        if ($color_id) {
            $tmp_stat->where('color_id', '=', $color_id);
                  
            $current_brand_stat->where('color_id', '=', $color_id);    
        }
        
        if ($composition_id) {
            $tmp_stat->where('composition_id', '=', $composition_id);
                  
            $current_brand_stat->where('composition_id', '=', $composition_id);   
        }
        
        if ($season_id) {
            $tmp_stat->where('season_id', '=', $season_id); 
                  
            $current_brand_stat->where('season_id', '=', $season_id);  
        }
        
        if ($shop_id) {
            $tmp_stat->where('shop_id', '=', $shop_id);
            $current_brand_stat->where('shop_id', '=', $shop_id);    
        }
        
        if ($from_price) {
            $tmp_stat->where('price', '>=', $from_price);
            $current_brand_stat->where('price', '>=', $from_price);   
        }
        if ($to_price) {
            $tmp_stat->where('price', '<=', $to_price);
            $current_brand_stat->where('price', '<=', $to_price); 
        }
        
        if ($use_denormalization && $isset_denormalized_data) {
            $tmp_stat = self::_get_denormalized_data('brand_id', $category_id, $brand_id, $color_id, $composition_id, $season_id, $shop_id, $price);    
        } else {  
            $tmp_stat = $tmp_stat
                    ->group_by('brand_id')
                    ->order_by('count', 'DESC');
                    
            if (!$category_id) {
                $tmp_stat->limit(15);    
            }
            $tmp_stat = $tmp_stat->execute()
                    ->as_array();
        }
                   
        
        $ids   = array();
        $found = false;
        foreach ($tmp_stat as $item) {
            $ids[] = $item['brand_id'];
            $stat[$item['brand_id']] = $item['count'];
            if ($brand && $brand_id == $item['brand_id']) {
                $found = true;   
            }    
        }
        if (!$found && $brand) {
            $ids[] = $brand_id;
            
            $current_brand_stat = $current_brand_stat
                                    ->where('brand_id', '=', $brand_id)
                                    ->execute()
                                    ->as_array();
                                    
            $stat[$brand_id] = $current_brand_stat[0]['count'];        
        }
        if (!count($ids)) {
            return array();    
        }
        $brands = array();
        $tmp_brands = ORM::factory('brand')
                        ->where('id', 'IN', $ids)
                        ->find_all()
                        ->as_array();
        foreach ($tmp_brands as $brand) {
            $brand = $brand->as_array(); 
            $brands[$brand['id']] = $brand;
            $brands[$brand['id']]['count'] = $stat[$brand['id']];            
        } 
        usort($brands, array(__CLASS__, '_compare'));
        
        Cache::instance()->set('catalog_brands_'.$category_id.'_'.$brand_id.'_'.$color_id.'_'.$composition_id.'_'.$season_id.'_'.$shop_id.'_'.$from_price.'_'.$to_price, $brands);
        return $brands;  
        
        /*$result = array(
            'main'  => array(),
            'other' => array(),
        );
        $i = 0;
        foreach ($brands as $brand) {
            if ($i < $limit) {
                $result['main'][] = $brand;         
            } else {
                $result['other'][] = $brand;    
            } 
            $i++;   
        }   
        
        Cache::instance()->set('catalog_brands_'.$category_id.'_'.$color_id.'_'.$composition_id.'_'.$season_id.'_'.$shop_id.'_'.$from_price.'_'.$to_price, $result);
        return $result;   */                                           
    }
    
    public function get_brand_by_url($url)
    {
        $brand = ORM::factory('brand')->where('url', '=', $url)->find();
        if (!$brand->loaded()) {
            throw new HTTP_Exception_404('Запись не найдена');      
        }
        return $brand;
    }
    
    public function get_first_letters()
    {
        if ($letters = Cache::instance()->get('brands_letters')) {
            return $letters;
        } 
        $_letters = DB::query(Database::SELECT, "SELECT SUBSTR(name, 1, 1) AS letter, COUNT(id) AS count FROM brands
                                                GROUP BY letter
                                                ORDER BY letter ASC")->execute()->as_array();
        $letters = array();
        foreach ($_letters as $item) {
            if (preg_match('/[0-9a-zA-Zа-яА-Я]{1}/i', $item['letter']) && $item['count'] > 40) {
                $letters[$item['letter']] = $item; 
            }  
        } 
                    
        Cache::instance()->set('brands_letters', $letters);
        return $letters; 
    }
    
    public function get_top_brands($letters)
    {
        if ($brands = Cache::instance()->get('top_brands')) {
            return $brands;
        } 
        $brands = array();
        foreach ($letters as $letter) {
            if ($letter == "'") {
                $letter = "\'";
            }
            
            $ids  = array();
            $_ids = DB::query(Database::SELECT, "SELECT id, (SELECT COUNT(*) FROM products WHERE brand_id = brands.id AND is_available = 1) AS count FROM brands
                                                WHERE name LIKE '{$letter}%'
                                                ORDER BY count DESC
                                                LIMIT 10")->execute()->as_array();
            foreach ($_ids as $item) {
                $ids[] = $item['id'];   
            }
            
            $brands[$letter] = ORM::factory('brand')
                                ->where('id', 'IN', $ids) 
                                ->find_all()
                                ->as_array(); 
        }    
        Cache::instance()->set('top_brands', $brands);
        return $brands;
    }
    
    public function get_brands_by_letter($letter)
    {
        if (!$letter) {
            throw new Model_Exception('Нет буквы');
        }
        $brands = ORM::factory('brand')
                    ->where('name', 'LIKE', DB::expr("'{$letter}%'")) 
                    ->order_by('name', 'ASC')
                    ->find_all()
                    ->as_array(); 
                    
        return $brands;
    }
    
}